package io.github.shenbinglife.springboot2.layui.admin.controller;

import io.github.shenbinglife.springboot2.layui.admin.entity.Dict;
import io.github.shenbinglife.springboot2.layui.admin.service.impl.DictionaryService;
import io.github.shenbinglife.springboot2.layui.common.model.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("admin/dictionaries")
public class DictionaryController {

    @Autowired
    private DictionaryService dictionaryService;

    @GetMapping("page")
    public Result<Page<Dict>> getDict(@RequestParam(required = false) String keyword,
                                      @RequestParam(defaultValue = "0") Integer page,
                                      @RequestParam(defaultValue = "20") Integer limit) {
        Page<Dict> dicts = dictionaryService.page(keyword, page - 1, limit);
        return Result.success(dicts);
    }

    @GetMapping
    public Result<List<Dict>> getDictByType(@RequestParam String type) {
        List<Dict> dictList = dictionaryService.findByType(type);
        return Result.success(dictList);
    }

    @GetMapping("{dictId}")
    public Result<Dict> getDict(@PathVariable("dictId") Long dictId) {
        return dictionaryService.getOptionalById(dictId)
                .map(Result::success)
                .orElse(Result.failure("字典条目不存在"));
    }

    @PostMapping("{dictId}")
    public Result<Void> update(@PathVariable("dictId") Long dictId, @RequestBody Dict dict) {
        dict.setId(dictId);
        dictionaryService.update(dict);
        return Result.success();
    }

    @PutMapping
    public Result<Dict> create(@RequestBody Dict dict) {
        dictionaryService.save(dict);
        return Result.success();
    }

    @DeleteMapping("{dictId}")
    public Result<Void> delete(@PathVariable("dictId") Long[] dictIds) {
        dictionaryService.deleteById(dictIds);
        return Result.success();
    }
}
